<template>
  <div class="auth-container">
    <el-card class="auth-card">
      <template #header>
        <div class="auth-header">
          <h2>🔐 登录</h2>
          <p>登录数字藏品交易平台</p>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="form.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            :loading="loading"
            style="width: 100%"
            size="large"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <el-divider>或</el-divider>

        <el-form-item>
          <el-button 
            @click="goToRegister" 
            style="width: 100%"
            size="large"
          >
            没有账号？去注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import userStore from '../store/userStore';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Login',
  setup() {
    const router = useRouter();
    const formRef = ref(null);
    const loading = ref(false);

    const form = reactive({
      username: '',
      password: '',
    });

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 50, message: '用户名长度为 3-50 个字符', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码至少 6 个字符', trigger: 'blur' },
      ],
    };

    const handleLogin = async () => {
      if (!formRef.value) return;

      try {
        await formRef.value.validate();
        loading.value = true;

        const response = await userStore.actions.login(form.username, form.password);
        
        if (response.success) {
          ElMessage.success('登录成功！欢迎回来');
          console.log('✅ 登录成功，当前用户:', userStore.state.user);
          console.log('✅ 登录状态:', userStore.state.isLoggedIn);
          console.log('✅ Token:', userStore.state.token);
          
          // 等待 Vue 响应式系统更新完成
          await nextTick();
          
          // 再延迟一下确保状态完全同步
          setTimeout(async () => {
            const redirect = router.currentRoute.value.query.redirect || '/';
            console.log('🚀 准备跳转到:', redirect);
            
            try {
              await router.push(redirect);
              console.log('✅ 跳转成功');
            } catch (err) {
              console.error('❌ 跳转失败:', err);
              // 如果跳转失败，尝试强制刷新
              window.location.href = redirect;
            }
          }, 300);
        } else {
          ElMessage.error(response.message || '登录失败');
        }
      } catch (error) {
        if (error !== false) {
          console.error('登录错误:', error);
          ElMessage.error(error.message || '登录失败');
        }
      } finally {
        loading.value = false;
      }
    };

    const goToRegister = () => {
      router.push('/register');
    };

    return {
      form,
      rules,
      formRef,
      loading,
      handleLogin,
      goToRegister,
    };
  },
};
</script>

<style scoped>
.auth-container {
  min-height: calc(100vh - 80px);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.auth-card {
  width: 100%;
  max-width: 450px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
}

.auth-header h2 {
  margin: 0 0 0.5rem 0;
  color: #303133;
}

.auth-header p {
  margin: 0;
  color: #909399;
  font-size: 0.9rem;
}
</style>

